<!-- 文章资讯 -->
<template>
	<view class="body">
		<cu-custom bgColor="bg-gradual-blue" :isBack="false" v-show="isShow">
			<!-- <block slot="backText">返回</block> -->
			<block slot="content">信息收集</block>
		</cu-custom>
		<view class="centerBox" v-if="!isLogin">
			<p class="p-5">您还暂未登录,请登录后进行操作!</p>
			<u-button type="success" size="medium" shape="circle" @click="toLogin">前往登录</u-button>
		</view>
		<view class="mainBox" v-if="isLogin">
			<text style="font-size: 40rpx;font-weight: 600;">调查信息上传</text>
			<u-form :model="model" ref="uForm" :rules="rules">
				<u-form-item label-width="150" :label-position="labelPosition" label="调查时间" prop="researchDate">
					<u-input placeholder="请输入调查时间 如yyyy-mm-dd" v-model="model.researchDate" type="date"
						:border="border"></u-input>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="物种照片" prop="photoFarm" label-width="150">
					<u-upload width="160" height="160" max-count="99" ref="upload" :file-list="model.photoFarm" :auto-upload="false"
						@on-list-change="showListFarm" @on-remove="removeList"></u-upload>
				</u-form-item>
				<u-form-item required label-width="150" :label-position="labelPosition" label="物种名称"
					prop="researchName">
					<u-input placeholder="请输入物种名称" :placeholder="placeholderSpecy" v-model="model.researchName"
						type="text" :border="border"></u-input>
				</u-form-item>
				<u-form-item label-width="150" :label-position="labelPosition" label="物种别称" prop="researchAnotherName">
					<u-input placeholder="请输入物种别称" v-model="model.researchAnotherName" type="text" :border="border">
					</u-input>
				</u-form-item>
				<u-form-item label-width="150" :label-position="labelPosition" label="拉丁学名" prop="researchLatinName">
					<u-input placeholder="请输入拉丁学名" v-model="model.researchLatinName" type="text" :border="border">
					</u-input>
				</u-form-item>
				<u-form-item label-width="120" :label-position="labelPosition" label="地址" prop="researchPlace">
					<u-input placeholder="请输入地址" v-model="model.researchPlace" type="text" :border="border"></u-input>
					<view class="cuIcon-locationfill" @click="chooseLocation"
						style="position: absolute;right: 0;top: 42px;z-index: 999;width: 60rpx;height: 40rpx;font-size: 40rpx;">
					</view>
				</u-form-item>
				<u-form-item label-width="120" :label-position="labelPosition" label="经纬度" prop="researchLnglat">
					<u-input placeholder="请输入经纬度" v-model="model.researchLnglat" type="text" :border="border"></u-input>
				</u-form-item>
				<u-form-item label-width="120" :label-position="labelPosition" label="海拔 / 米" prop="researchAltitude">
					<u-input placeholder="海拔" v-model="model.researchAltitude" type="number" :border="border"></u-input>
				</u-form-item>
				<u-form-item label="生活环境" :label-position="labelPosition" label-width="150">
					<u-checkbox-group @change="researchEnvironmentChange">
						<u-checkbox v-model="item.checked" v-for="(item, index) in researchEnvironmentOptions"
							:key="index" :name="index+1">
							{{ item.name }}
						</u-checkbox>
					</u-checkbox-group>
				</u-form-item>
				<u-form-item label="传播方式" :label-position="labelPosition" label-width="150">
					<u-checkbox-group @change="researchSpreadChange">
						<u-checkbox v-model="item.checked" v-for="(item, index) in researchSpreadOptions" :key="index"
							:name="index+1">
							{{ item.name }}
						</u-checkbox>
					</u-checkbox-group>
				</u-form-item>
				<u-form-item label-width="120" :label-position="labelPosition" label="发生面积 单位:平方米" prop="researchArea">
					<u-input placeholder="发生面积" v-model="model.researchArea" type="number" :border="border"></u-input>
				</u-form-item>
				<u-form-item label-width="120" :label-position="labelPosition" label="发生密度 单位:株/平方米"
					prop="researchDensity">
					<u-input placeholder="发生密度" v-model="model.researchDensity" type="number" :border="border">
					</u-input>
				</u-form-item>
				<u-form-item label="优势度" :label-position="labelPosition">
					<u-radio-group v-model="model.researchDominance">
						<u-radio v-for="(item, index) in researchDominanceOptions" :key="index" :name="item.value"
							:disabled="item.disabled">
							{{ item.name }}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label-width="120" :label-position="labelPosition" label="盖度 百分比表示" prop="researchCovery">
					<u-input placeholder="盖度" v-model="model.researchCovery" type="number" :border="border"></u-input>
				</u-form-item>
				<u-form-item label-width="120" :label-position="labelPosition" label="频度 百分比表示"
					prop="researchFrequence">
					<u-input placeholder="频度" v-model="model.researchFrequence" type="number" :border="border">
					</u-input>
				</u-form-item>
				<u-form-item label-width="120" :label-position="labelPosition" label="伴生物种" prop="researchMutualism">
					<u-input placeholder="伴生物种" v-model="model.researchMutualism" type="text" :border="border">
					</u-input>
				</u-form-item>
				<u-form-item label="利用价值" :label-position="labelPosition" label-width="150">
					<u-checkbox-group @change="researchUsageChange">
						<u-checkbox v-model="item.checked" v-for="(item, index) in researchUsageOptions" :key="index"
							:name="index+1">
							{{ item.name }}
						</u-checkbox>
					</u-checkbox-group>
				</u-form-item>
				<u-form-item label-width="160" :label-position="labelPosition" label="农业危害" prop="researchAgriculture">
					<u-input placeholder="请输入农业危害" v-model="model.researchAgriculture" type="textarea" :border="border">
					</u-input>
				</u-form-item>
				<u-form-item label-width="160" :label-position="labelPosition" label="林业危害" prop="researchForestry">
					<u-input placeholder="请输入林业危害" v-model="model.researchForestry" type="textarea" :border="border">
					</u-input>
				</u-form-item>
				<u-form-item label-width="160" :label-position="labelPosition" label="养殖业危害" prop="researchBreeding">
					<u-input placeholder="请输入养殖业危害" v-model="model.researchBreeding" type="textarea" :border="border">
					</u-input>
				</u-form-item>
				<u-form-item label="交通航运影响" :label-position="labelPosition">
					<u-radio-group v-model="model.researchTraffic">
						<u-radio v-for="(item, index) in researchTrafficOptions" :key="index" :name="item.value"
							:disabled="item.disabled">
							{{ item.name }}
						</u-radio>
					</u-radio-group>
				</u-form-item>
			</u-form>
			<u-button :ripple="true" ripple-bg-color="#909399" class="btn" type="success" shape="circle" @click="open">
				保存</u-button>
			<view class="blockView"></view>
		</view>
		<u-select v-model="show" :list="list"></u-select>
	</view>
</template>

<script>
	import {
		getNoticeList
	} from '../../common/api/notice.js'
	import {
		getDicts
	} from '../../common/api/dict/data.js'
	import {
		ToDegrees
	} from '../../common/utils/lnglatTransform.js'
	import {
		getImgToBase64
	} from '../../common/base64.js'
	import {
		imageRecognition
	} from '../../common/api/imgRecognition.js'
	import {
		uploadImg,
		addResearchInfo,
		imgBase64Upload,
		geoCoder,
		listRegion,
		fullAddress
	} from '../../common/api/researchInfo.js'
	import {
		researchEnvironmentOptions,
		researchSpreadOptions,
		researchDominanceOptions,
		researchUsageOptions
	} from '../../common/config/dict.js'
	export default {
		data() {
			return {
				border: true,
				//配置文件
				researchEnvironmentOptions: [],
				researchSpreadOptions: [],
				researchDominanceOptions: [],
				researchUsageOptions: [],
				labelPosition: 'top',
				model: {
					researchDate: '',
					placeholderSpecy: '',
					researchName: '',
					researchAnotherName: '',
					researchLatinName: '',
					researchPlace: '',
					researchLnglat: '',
					researchAltitude: '',
					researchArea: '',
					researchDensity: '',
					researchCovery: '',
					researchFrequence: '',
					researchMutualism: '',
					researchAgriculture: '',
					researchForestry: '',
					researchBreeding: '',
					researchImage: [],
					regionId: 0
				},
				temLen: 0,
				location: '',
				rules: {
					researchName: [{
						required: true,
						message: '物种名称不能为空',
						trigger: ['change', 'blur']
					}],
					researchAltitude: [{
						type: 'number',
						message: '海拔必须为数字值'
					}],
					researchArea: [{
						type: 'number',
						message: '发生面积必须为数字值'
					}],
					researchDensity: [{
						type: 'number',
						message: '发生密度必须为数字值'
					}],
					researchCovery: [{
						type: 'number',
						message: '盖度必须为数字值'
					}],
					researchFrequence: [{
						type: 'number',
						message: '频度必须为数字值'
					}],
				},
				placeholderSpecy: '请输入物种名称',
				isShow: true,
				queryParam: {
					pageNum: 1,
					pageSize: 10
				},
				checkboxList: [{
						name: '苹果',
						checked: false,
						disabled: false
					},
					{
						name: '雪梨',
						checked: false,
						disabled: false
					},
					{
						name: '柠檬',
						checked: false,
						disabled: false
					}
				],
				researchTrafficOptions: [{
						name: '否',
						value: 1,
						disabled: false
					},
					{
						name: '是',
						value: 2,
						disabled: false
					}
				]
			};
		},
		props: {
			isLogin: {
				type: Boolean,
				default: false
			},
		},
		methods: {
			open() {
				this.model.researchTraffic = this.model.researchTraffic - 1
				try {
					this.model.researchImage = this.model.researchImage.join(",")
				} catch (err) {
					console.log(err)
				}


				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('验证通过');
					} else {
						console.log('验证失败');
						return;
					}
				})

				console.log(this.model)

				let _this = this
				
				const submitFun = async () => {
					
					/**
					 * 更改location的内容
					 **/
					// const resRegionName = await geoCoder(_this.location)
					// const regionName = resRegionName[1].data.result.address_reference.town.title
					// console.log(regionName)
					// const resRegionId = await listRegion({
					// 	regionName: regionName
					// })
					// _this.model.regionId = resRegionId[1].data.data[0].regionId
					// console.log(_this.model.regionId)
					
					
					const res = await addResearchInfo(_this.model)
					// 判断是否提交成功
					if (res[1].data.code == 200) {
						uni.showToast({
							title: res[1].data.msg
						});
						// 恢复初始值
						setTimeout(() => {
							_this.model = {}
							_this.temLen = 0
							// 清除图片
							_this.$refs.upload.clear()
							_this.researchEnvironmentOptions.map(val => {
								val.checked = false;
							})
							_this.researchSpreadOptions.map(val => {
								val.checked = false;
							})
							_this.researchDominanceOptions.map(val => {
								val.checked = false;
							})
							_this.researchUsageOptions.map(val => {
								val.checked = false;
							})
							_this.researchTrafficOptions.map(val => {
								val.checked = false;
							})
						}, 300)
					}
				}
				// 执行提交操作
				submitFun()
			},
			// 初始化
			init() {
				this.researchEnvironmentOptions = researchEnvironmentOptions
				this.researchSpreadOptions = researchSpreadOptions
				this.researchDominanceOptions = researchDominanceOptions
				this.researchUsageOptions = researchUsageOptions
			},
			researchEnvironmentChange(e) {
				console.log(e.join(','))
				this.model.researchEnvironment = e.join(",")
			},
			researchSpreadChange(e) {
				console.log(e.join(','))
				this.model.researchSpread = e.join(",")
			},
			researchUsageChange(e) {
				console.log(e.join(','))
				this.model.researchUsage = e.join(",")
			},
			removeList(index, lists) {
				this.model.researchImage.splice(index, 1)
				// console.log(this.model.researchImage)
			},
			// 图片类别获取，实现图像识别
			showListFarm(res) {
				let _this = this
				console.log(res.length, _this.temLen)
				if (res.length < 1 || res.length <= _this.temLen) {
					// 设置temLen的值
					_this.temLen = res.length
					return;
				}
				// 设置temLen的值
				_this.temLen = res.length

				let len = res.length
				// console.log(res.length)
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				uni.getFileSystemManager().readFile({
					filePath: res[len - 1].file.path, //选择图片返回的相对路径
					encoding: 'base64', //编码格式
					success: res => { //成功的回调
						// console.log(res);
						let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符，在页面无法显示的哦

						imgBase64Upload({
							base64Data: 'data:image/jpeg;base64,' + res.data
						}).then(rss => {
							console.log(rss[1].data.fileName)
							// _this.model.researchImage += rss[1].data.fileName + ","
							_this.model.researchImage.push(rss[1].data.fileName)
						})

						imageRecognition(res.data).then(rs => {
							// console.log(rs[1].data)
							let list = JSON.parse(rs[1].data.msg);
							// console.log(list, typeof list);
							if (
								list.result.plant.result[0].name == "非植物" &&
								list.result.animal.result[0].name == "非动物"
							) {
								_this.placeholderSpecy = "未知";
							} else if (list.result.plant.result[0].name == "非植物") {
								_this.placeholderSpecy =
									"该动物可能为：" + list.result.animal.result[0].name;
							} else if (list.result.animal.result[0].name == "非动物") {
								_this.placeholderSpecy =
									"该植物可能为：" + list.result.plant.result[0].name;
							}
							uni.hideLoading()
						})
					},
					fail: (e) => {
						console.log("图片转换失败");
						uni.hideLoading()
					}
				})

				setTimeout(() => {
					console.log(_this.model.researchImage)
				}, 1000)
				// uni.showLoading({
				// 	title: '加载中',
				// 	mask: true
				// });
				console.log(res[0].file)
				// getImgToBase64(res[0].file).then((res) => {
				// 	console.log(res);
				// 	uni.hideLoading()
				// })
			},
			// 定位
			chooseLocation() {
				let _this = this
				uni.chooseLocation({
					success: async function(res) {
						console.log(res)
						// console.log('位置名称：' + res.name);
						// console.log('详细地址：' + res.address);
						// _this.model.researchPlace = res.address
						_this.location = res.latitude + "," + res.longitude
						_this.model.researchLnglat = '经度：' + ToDegrees(res.longitude) + "，" + '纬度：' +
							ToDegrees(res.latitude)
							
						const resRegionName = await geoCoder(_this.location)
						const regionName = resRegionName[1].data.result.address_reference.town.title
						// console.log(regionName)
						const resRegionId = await listRegion({
							regionName: regionName
						})
						_this.model.regionId = resRegionId[1].data.data[0].regionId
						// console.log(_this.model.regionId)
						const addressObj = await fullAddress({regionId:_this.model.regionId})
						// console.log(addressObj[1].data.msg)
						_this.model.researchPlace = addressObj[1].data.msg
					}
				});
			},
			// 暂未登录，去登录
			toLogin() {
				uni.navigateTo({
					url: '../login/login'
				})
			},
			// tabs通知swiper切换
			tabsChange(index) {
				this.swiperCurrent = index;
			},
			// swiper-item左右移动，通知tabs的滑块跟随移动
			transition(e) {
				let dx = e.detail.dx;
				this.$refs.uTabs.setDx(dx);
			},
			// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
			// swiper滑动结束，分别设置tabs和swiper的状态
			animationfinish(e) {
				let current = e.detail.current;
				this.$refs.uTabs.setFinishCurrent(current);
				this.swiperCurrent = current;
				this.current = current;
			},
			// scroll-view到底部加载更多
			onreachBottom() {

			},
			// tabSelect(e) {
			// 	this.TabCur = e.currentTarget.dataset.id;
			// 	this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
			// },
		},
		mounted() {
			this.init()
		},
		onReady() {
			if (this.isLogin) {
				this.$refs.uForm.setRules(this.rules);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.body {
		background-color: #fff;
	}

	.borderBottom {
		border-bottom: 1px solid #f2f2f2;
	}

	.noticeList {
		height: 120rpx;
		width: 100%;
		padding: 0 10px;
		margin: 10px 0;
	}

	.noticeItem {
		height: 100%;
		width: 100%;
		background-color: #fff;
		border-radius: 6px;
		padding: 10px;
	}

	.mainBox {
		padding: 20rpx 28rpx;

		.btn {
			margin-top: 30rpx;
		}
	}

	.centerBox {
		flex-direction: column;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 34vh 0;

		.p-5 {
			padding: 36px 0;
			color: #666;
		}
	}

	.blockView {
		width: 100%;
		height: 120rpx;
	}
</style>
